﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Linq.Expressions;
using System.Web.Routing;

namespace MvcPatch
{
    public class RedirectToActionResult<TController> : ActionResult where TController : Controller
    {
        public RedirectToActionResult(Expression<Action<TController>> action, RouteCollection routeCollection)
        {
            this.Expression = action;
            this.Routes = routeCollection;
        }

        public Expression<Action<TController>> Expression { get; private set; }

        public RouteCollection Routes { get; private set; }

        public RedirectToActionResult(Expression<Action<TController>> action)
            : this(action, RouteTable.Routes) { }

        public override void ExecuteResult(ControllerContext context)
        {
            var pathBuilder = RouteExpression.Parse(this.Expression, context.RequestContext);
            var path = pathBuilder.GetVirtualPath(this.Routes, context.RequestContext);
            new RedirectResult(path.VirtualPath).ExecuteResult(context);
        }
    }
}
